#!/usr/bin/env node

const len = process.argv.length,
      arr = [],
      err = console.error,
      log = console.log,
      exit = process.exit,
      stdout = process.stdout,
      stdin = process.stdin;
let addNum = 0,
    temp = process.argv[2],
    Hnum = 0;
function wrongObj(a){
    if(Number.isNaN(a)){
      log('请输入数字！');
      return 0;     
    }else if(a < 0){
      log('请输入大于0的数字');
      return 0;
    }else if(a > 1){
      log('请输入小于1的数字');
      return 0;
    }
    return a;
}
function interInput(){
  log('请输入信源2概率分布(按Ctrl+c退出)');
  let i = 1,
      arr = [0],
      hnum = 0,
      add_p = 0;
  stdin.resume();
  stdout.write(`p${i}:`);
  stdin.on('data',data => {
    arr[i] = Number(data);
    arr[i] = wrongObj(arr[i]);
    hnum = hnum + arr[i]*Math.log(arr[i],2);
    add_p = add_p + Number(data);
    stdout.write(`p${++i}:`);
  });
  process.on('SIGTSTP',() => {
    if(add_p != 1){
      log('概率空间分布不封闭，请重新输入！');
      i = 1;
      interInput();
    }else{
      log(`\n h(P) = ${-parseInt(hnum * 1000)/1000} bit`)
    } 
  });
}
function outPut(num){
  wrongObj(num);
  addNum += num;
  Hnum += -num*Math.log(num,2);
  
}
if(len < 4) {
  let temp = process.argv[2] || '';
  let arr = temp.split(',');
  for(let i = 0;i < arr.length;i++){ 
      if(Number.isNaN(Number(arr[i]))){
         log('参数格式不正确，请重新输入！');
         i = arr.length;
         interInput();
      }else if(len === 3 && !(Number.isNaN(Number(arr[i]))) && arr.length == 1){
         log('命令行参数不能小于两个，请重新输入！');
         i = arr.length;
         interInput();
      }else{
         outPut(Number(arr[i]));
         if(addNum != 1){
            log('概率空间分布不封闭，请重新输入！');
            i = arr.length;
            interInput();
         }else{
            Hnum = parseInt(Hnum * 1000)/1000;
            log(`h(p)=${Hnum} bit`);
         }
      }
  }
}else{
  for(let i = 2;i <= len-1;i++){
    arr[i-2] = Number(process.argv[i]);
    outPut(arr[i-2]); 
  } 
  if(addNum != 1){
    log('概率空间分布不封闭，请重新输入！');
    interInput();
  }else{
    Hnum = parseInt(Hnum * 1000)/1000;
    log(`h(p)=${Hnum} bit`);
  }
}
